﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public class StringHelper
    {

        private StringHelper() { }

        public static bool IsValidString(string text)
        {
            return (text != null && text != string.Empty && text.Trim().Length > 0);
        }

        public static string ArrayOfBytesToString(byte[] chars)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string content = encoding.GetString(chars);
            return content;
        }

        public static byte[] StringToByteArray(string XmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] bytearray = encoding.GetBytes(XmlString);
            return bytearray;
        }


        public static string BytesArrayToHexString(byte[] data)
        {
            return BitConverter.ToString(data).Replace("-", "");
        }

        public static byte[] HexStringToBytesArray(string text)
        {
            text = text.Replace(" ", "");
            int l = text.Length;
            byte[] buffer = new byte[l / 2];
            for (int i = 0; i < l; i += 2)
            {
                buffer[i / 2] = Convert.ToByte(text.Substring(i, 2), 16);
            }
            return buffer;
        }


        public static string ToBase64String(byte[] buf)
        {
            return System.Convert.ToBase64String(buf);
        }

        public static byte[] FromBase64String(string s)
        {
            return System.Convert.FromBase64String(s);
        }

        public static string NullToEmpty(string value)
        {
            return value == null ? string.Empty : value;
        }
        /// <summary>
        /// 长字符串截取
        /// </summary>
        /// <param name="text">原始字符串</param>
        /// <param name="len">留取长度</param>
        /// <returns></returns>
        public static string EllipsisText(string text, int len)
        {
            int iLen = len;
            if (iLen > 0)
            {
                System.Text.Encoding gb2312 = System.Text.Encoding.GetEncoding("gb2312");
                byte[] bytes = gb2312.GetBytes(text);
                int left = iLen * 2;
                if (bytes.Length > left)
                {
                    if (bytes[left - 1] > 128)
                    {
                        int half = 1;
                        for (int i = left - 2; i >= 0; i--)
                        {
                            if (bytes[i] > 128)
                                half = 1 - half;
                            else
                                break;
                        }
                        if (1 == half)
                            left++;
                    }
                    byte[] subBytes = new byte[left];
                    Array.Copy(bytes, subBytes, left);
                    text = gb2312.GetString(subBytes);
                }
            }
            return text;
        }
        /// <summary>
        /// 长字符串截取
        /// </summary>
        /// <param name="text">原始字符串</param>
        /// <param name="len">留取长度</param>
        /// <returns></returns>
        public static string EllipsisText(string text, int len, string placeholder)
        {
            int iLen = len;
            if (iLen > 0)
            {
                System.Text.Encoding gb2312 = System.Text.Encoding.GetEncoding("gb2312");
                byte[] bytes = gb2312.GetBytes(text);
                int left = iLen * 2;
                if (bytes.Length > left)
                {
                    if (bytes[left - 1] > 128)
                    {
                        int half = 1;
                        for (int i = left - 2; i >= 0; i--)
                        {
                            if (bytes[i] > 128)
                                half = 1 - half;
                            else
                                break;
                        }
                        if (1 == half)
                            left++;
                    }
                    byte[] subBytes = new byte[left];
                    Array.Copy(bytes, subBytes, left);
                    text = gb2312.GetString(subBytes) + placeholder;
                }
            }
            return text;
        }
        public static List<string> GetSMSSplitString(string srcStr, int maxLength, Encoding coder, string preStr, bool hasPreStr)
        {
            List<string> messages = new List<string>();

            byte[] buffer = coder.GetBytes(srcStr);

            int total = buffer.Length;

            int preCount = hasPreStr ? coder.GetByteCount(preStr + "：") : 0;

            int pageCount = 1;

            //分页小于10页时
            if (total <= (maxLength - 10 - preCount) * 9)
            {
                //total ＋ (6 ＋ preCount) * pageCount + 4 * pageCount = maxLength * pageCount 
                pageCount = total / (maxLength - 10 - preCount);

                pageCount += (total % (maxLength - 10 - preCount) != 0 ? 1 : 0);
            }
            //分页大于10页时
            else
            {
                //total ＋ ( 6 ＋ preCount) * pageCount ＋ 4 * pageCount ＋ 4 * pageCount － 18 ＝maxLength * pageCount
                pageCount = (total - 18) / (maxLength - 14 - preCount);

                pageCount += ((total - 18) % (maxLength - 14 - preCount) != 0 ? 1 : 0);
            }

            int firstStrIndex = 0;
            int curFlag = 0;

            for (int j = 0; j < pageCount; j++)
            {
                string header = hasPreStr ? string.Format("({0}/{1}){2}：", (j + 1).ToString(), pageCount.ToString(), preStr) : string.Format("({0}/{1})", (j + 1).ToString(), pageCount.ToString());

                if (pageCount == 1)
                {
                    header = hasPreStr ? string.Format("{0}：", preStr) : "";
                }

                int headerCount = coder.GetBytes(header).Length;

                int size = maxLength - headerCount;
                int getCount = (total - curFlag) > size ? size : (total - curFlag);
                string tempStr = coder.GetString(buffer, curFlag, getCount);

                string srcTempStr = srcStr.Substring(firstStrIndex, tempStr.Length);
                if (tempStr != srcTempStr)
                {
                    tempStr = tempStr.Substring(0, tempStr.Length - 1);
                    byte[] tempBuf = new byte[maxLength];
                    int tempCount = coder.GetBytes(tempStr, 0, tempStr.Length, tempBuf, 0);
                    curFlag += tempCount;
                }
                else
                {
                    curFlag += getCount;
                }
                firstStrIndex += tempStr.Length;
                tempStr = header + tempStr;

                messages.Add(tempStr);

            }
            //}
            return messages;
        }

        public static Dictionary<string, string> SplitToDictionary(string s, char split1, char split2)
        {
            string[] dicGroup = s.Split(split1);
            Dictionary<string, string> dics = new Dictionary<string, string>();
            foreach (string dic in dicGroup)
            {
                string[] kv = dic.Split(split2);
                if (kv.Length == 2)
                {
                    dics.Add(kv[0], kv[1]);
                }
            }
            return dics;
        }


        /// <summary>
        /// SQL过滤敏感字符
        /// </summary>
        /// <param name="InText">要特殊过滤的字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string SqlFilterSpecial(string InText)
        {
            if (InText == "") //如果字符串为空，直接返回。
            {
                return InText;
            }
            else
            {
                InText = InText.Replace("and ", "");
                InText = InText.Replace("exec ", "");
                InText = InText.Replace("insert ", "");
                InText = InText.Replace("select ", "");
                InText = InText.Replace("delete ", "");
                InText = InText.Replace("update ", "");
                InText = InText.Replace(" and", "");
                InText = InText.Replace(" exec", "");
                InText = InText.Replace(" insert", "");
                InText = InText.Replace(" select", "");
                InText = InText.Replace(" delete", "");
                InText = InText.Replace(" update ", "");
                InText = InText.Replace("chr ", "");
                InText = InText.Replace("mid ", "");
                InText = InText.Replace(" chr", "");
                InText = InText.Replace(" mid", "");
                InText = InText.Replace("master ", "");
                InText = InText.Replace(" master", "");
                InText = InText.Replace("or ", "");
                InText = InText.Replace(" or", "");
                InText = InText.Replace("truncate ", "");
                InText = InText.Replace("char ", "");
                InText = InText.Replace("declare ", "");
                InText = InText.Replace("join ", "");
                InText = InText.Replace("union ", "");
                InText = InText.Replace("truncate ", "");
                InText = InText.Replace(" char", "");
                InText = InText.Replace(" declare", "");
                InText = InText.Replace(" join", "");
                InText = InText.Replace(" union", "");
                InText = InText.Replace("'", "");
                InText = InText.Replace("<", "");
                InText = InText.Replace(">", "");
                InText = InText.Replace("%", "");
                InText = InText.Replace("'delete", "");
                InText = InText.Replace("''", "");
                InText = InText.Replace("\"\"", "");
                InText = InText.Replace(",", "");
                InText = InText.Replace(">=", "");
                InText = InText.Replace("=<", "");
                InText = InText.Replace("--", "");
                InText = InText.Replace("_", "");
                InText = InText.Replace(";", "");
                InText = InText.Replace("||", "");
                InText = InText.Replace("[", "");
                InText = InText.Replace("]", "");
                InText = InText.Replace("&", "");
                InText = InText.Replace("/", "");
                InText = InText.Replace("?", "");
                InText = InText.Replace(">?", "");
                InText = InText.Replace("?<", "");
                InText = InText.Replace(" ", "");
                return InText;
            }
        }

        public static bool SqlCheckSpecial(string sqlText)
        {
            if (string.IsNullOrEmpty(sqlText))
                return false;
            sqlText = sqlText.ToLower();
            if (StringIndexOf(sqlText, "select") && StringIndexOf(sqlText, "from"))
                return false;
            if (StringIndexOf(sqlText, "create") && StringIndexOf(sqlText, "login"))
                return false;
            if (StringIndexOf(sqlText, "create") && StringIndexOf(sqlText, "user"))
                return false;
            if (StringIndexOf(sqlText, "create") && StringIndexOf(sqlText, "table"))
                return false;
            if (StringIndexOf(sqlText, "alter") && StringIndexOf(sqlText, "table"))
                return false;
            if (StringIndexOf(sqlText, "drop") && StringIndexOf(sqlText, "table"))
                return false;
            if (StringIndexOf(sqlText, "drop") && StringIndexOf(sqlText, "database"))
                return false;
            if (StringIndexOf(sqlText, "create") && StringIndexOf(sqlText, "view"))
                return false;
            if (StringIndexOf(sqlText, "alter") && StringIndexOf(sqlText, "view"))
                return false;
            if (StringIndexOf(sqlText, "drop") && StringIndexOf(sqlText, "view"))
                return false;
            if (StringIndexOf(sqlText, "create") && StringIndexOf(sqlText, "proc"))
                return false;
            if (StringIndexOf(sqlText, "alter") && StringIndexOf(sqlText, "proc"))
                return false;
            if (StringIndexOf(sqlText, "drop") && StringIndexOf(sqlText, "proc"))
                return false;
            if (StringIndexOf(sqlText, "create") && StringIndexOf(sqlText, "function"))
                return false;
            if (StringIndexOf(sqlText, "alter") && StringIndexOf(sqlText, "function"))
                return false;
            if (StringIndexOf(sqlText, "drop") && StringIndexOf(sqlText, "function"))
                return false;
            if (StringIndexOf(sqlText, "insert") && StringIndexOf(sqlText, "values"))
                return false;
            if (StringIndexOf(sqlText, "insert") && StringIndexOf(sqlText, "select"))
                return false;
            if (StringIndexOf(sqlText, "--"))
                return false;
            if (StringIndexOf(sqlText, "--"))
                return false;
            if (StringIndexOf(sqlText, "/*"))
                return false;
            if (StringIndexOf(sqlText, "*/"))
                return false;
            return true;
        }

        public static bool StringIndexOf(string inputString, string indexString)
        {
            if (string.IsNullOrEmpty(inputString))
                return false;
            if (inputString.IndexOf(indexString) > -1)
                return true;
            return false;
        }
        /// <summary>
        /// 获取字符串类型的主键
        /// </summary>
        /// <returns></returns>
        public static string GetNewId()
        {
            //return Guid.NewGuid().ToString();
            return CreateNewId();
        }
        /// <summary>
        /// 创建不重复的Id
        /// </summary>
        /// <returns></returns>
        private static string CreateNewId()
        {
            string id = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
            string guid = Guid.NewGuid().ToString().Replace("-", "");

            id += guid.Substring(0, 10);
            return id;
        }
    }
}
